package com.shamrock.oauth.api.service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qq.connect.utils.RandomStatusGenerator;
import com.shamrock.oauth.api.entity.User;
import com.shamrock.oauth.api.httpclient.AccessToken;
import com.shamrock.oauth.api.httpclient.HttpClients;
import com.shamrock.oauth.api.httpclient.PostParameter;
import com.shamrock.oauth.util.Config;
import com.shamrock.oauth.util.JSONObject;

/**
 * 微信第三方登录
 * 第一步：授权，获取code
 * 第二步：通过code,获取accessToken，openid
 * 第三步:通过accessToken、openid获取用户信息
 * @author GunnyZeng
 *
 */
public class WeiXinOAuthApi implements OAuthApiService{

	private String appid =    Config.getValue("weixin_appid").trim();
	private String secret =    Config.getValue("weixin_secret").trim();
	private String redirect_URI = Config.getValue("weixin_redirect_URI").trim();
	private String getUserInfoURL = Config.getValue("weixin_userinfpApiUrl").trim();
	private String authorizeURL = Config.getValue("weixin_authorizeURL").trim();
	private String accessTokenURL = Config.getValue("weixin_access_token_URL").trim();
	private String scope = Config.getValue("weixin_scope").trim();
	HttpClients client  = new HttpClients();

	@Override
	public String authorize() {
		String state = RandomStatusGenerator.getUniqueState();
        if(scope != null && !scope.equals(""))
        	 return (new StringBuilder()).append(authorizeURL).append("?appid=").append(appid).append("&redirect_uri=").append(redirect_URI).append("&response_type=").append("code").append("&state=").append(state).append("&scope=").append(scope).append("#wechat_redirect").toString();
        else
            return (new StringBuilder()).append(authorizeURL).append("?appid=").append(appid).append("&redirect_uri=").append(redirect_URI).append("&response_type=").append("code").append("&state=").append(state).append("#wechat_redirect").toString();
    
	}

	@Override
	public User getUser(Object parame) throws Exception {
		 String code = (String) parame;
		 AccessToken accessToken = getAccessToken(code);

         User user =  new User();
         if (accessToken.getAccessToken().equals("")) {
             throw new Exception("授权失败！");
         } else {
             String openID = accessToken.getUserUid();
             //获取用户信息
             JSONObject json = showUser(accessToken);
             
             if (json!=null&&json.keys().hasNext()) {
                 user.setId(openID);
                 user.setAvatarLarge(json.getString("headimgurl"));
                 user.setNickName(json.getString("nickname"));
                 user.setGender(json.getString("sex"));
                 user.setCity(json.getString("city"));
                 user.setProvince(json.getString("province"));
                 user.setSource("微信");
                 
             } else {
            	 throw new Exception("很抱歉，我们没能正确获取到您的信息! ");
             }
         }
         return user;
	}
	
	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	private AccessToken getAccessToken(String code) throws Exception{
		return new AccessToken(client.post(
				accessTokenURL,
				new PostParameter[] {
						new PostParameter("appid", appid),
						new PostParameter("secret",secret),
						new PostParameter("grant_type", "authorization_code"),
						new PostParameter("code", code),
						}, false, null),"openid");
	}
	/**
	 * 授权后获取用户json数据
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	 private JSONObject showUser(AccessToken accessToken) throws Exception
		    {
		        return client.get(getUserInfoURL, new PostParameter[] {
		            new PostParameter("openid", accessToken.getUserUid()), 
		            new PostParameter("access_token", accessToken.getAccessToken())
		        },accessToken.getAccessToken()).asJSONObject();
		    }


}
